package com.mall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.mall.product.service.CategoryBrandRelationService;
import com.mall.product.vo.Category2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.utils.PageUtils;
import com.common.utils.Query;

import com.mall.product.dao.CategoryDao;
import com.mall.product.entity.CategoryEntity;
import com.mall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    RedissonClient redissonClient;
    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1 查出所有分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //2 组装成父子的树形结构
            //1)找到所有的父分类
        List<CategoryEntity> level1 = categoryEntities.stream().filter(categoryEntity ->
            categoryEntity.getParentCid() == 0
        ).map(menu->{
            List<CategoryEntity> children = getChildren(menu,categoryEntities);
            menu.setChildren(children);
            return menu;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return level1;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //todo 1.检查当前删除的菜单，是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);

        return parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新所有的数据
     *
     *  @CacheEvict 缓存失效模式
     *
     *
     * @param category
     */
    @CacheEvict(value = "category",key = "'getLevel1Categorys'")
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());

    }

    /**
     * //代表将当前的结果进行缓存，如果缓存中有，方法不调用，如果没有，最后将方法的结果放入缓存
     * key自动生成，缓存的名字：：自动生成的key
     * 缓存的value值默认使用jdk的序列化机制，将序列化后的数据存到redis
     * 默认ttl -1 永久
     * 自定义
     *      key   key属性指定，接受spel表达式
     *      存活时间    spring.cache.redis.time-to-live=3600000
     *      数据保存为json
     * @return
     */
    @Cacheable(value = {"category"},key = "'getLevel1Categorys'")
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("getLevel1Categorys.....");
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;


    }

    /**
     * 1. 空结果缓存：解决缓存穿透
     * 2. 设置过期时间：解决缓存雪崩
     * 3. 加锁：解决缓存击穿
     * @return
     */
    @Override
    public Map<String, List<Category2Vo>> getCatalogJson() {
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        if (StringUtils.isEmpty(catalogJson)){
            System.out.println("缓存不命中，查询数据库。。。。");
            Map<String, List<Category2Vo>> catalogJsonFromDb =catalogJsonFromDb = getCatalogJsonFromDbWithRedissonLock();
             return catalogJsonFromDb;
        }
        System.out.println("缓存命中，直接返回。。。。");
        Map map = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Category2Vo>>>(){});
        return map;


    }

    /**
     * 缓存里的数据如何和数据库保持一致
     * @return
     */
    private  Map<String, List<Category2Vo>> getCatalogJsonFromDbWithRedissonLock() {
        //1. 锁的名字
        RLock catalogJson = redissonClient.getLock("catalogJson-lock");
        catalogJson.lock();
        Map<String, List<Category2Vo>> dataFromDB = null;
            try {
                dataFromDB = getDataFromDB();
            }finally {
                catalogJson.unlock();
            }

            //原子删除锁
            return dataFromDB;
    }
    /**
     * 使用redis获取
     * @return
     */
    private  Map<String, List<Category2Vo>> getCatalogJsonFromDbWithRedisLock() {
        //加锁，为了控制缓存击穿，因此进来之后还要判断是否缓存中是否有
        //占分布式锁,占锁设置过期时间和释放锁需要原子操作，
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid,30,TimeUnit.SECONDS);
        if (lock){ //枷锁成功
            Map<String, List<Category2Vo>> dataFromDB = null;
            try {
                dataFromDB = getDataFromDB();
            }finally {
                String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n" +
                        "    return redis.call(\"del\",KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end";
                Integer lock1 = redisTemplate.execute(new DefaultRedisScript<Integer>(script, Integer.class), Arrays.asList("lock"), uuid);
            }

//            String lock1 = redisTemplate.opsForValue().get("lock");
//            if (lock1.equals(uuid))
//                redisTemplate.delete("lock");

            //原子删除锁
            return dataFromDB;
        }else { //加锁失败
            //重试
            return getCatalogJsonFromDbWithRedisLock();
        }


    }

    private Map<String, List<Category2Vo>> getDataFromDB() {
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        //如果缓存中不空，直接返回结果
        if (!StringUtils.isEmpty(catalogJson)) {
            Map map = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Category2Vo>>>() {
            });
            return map;
        }
        /**
         * 1. 将数据库的多次查询变为1次
         */
        System.out.println("查询了数据库。。。。");
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //查出所有分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
        //封装数据
        Map<String, List<Category2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());

            List<Category2Vo> collect = null;
            if (categoryEntities != null) {
                collect = categoryEntities.stream().map(l2 -> {
                    Category2Vo category2Vo = new Category2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    List<CategoryEntity> categoryEntities1 = getParent_cid(selectList, l2.getCatId());
                    if (categoryEntities1 != null) {

                        List<Category2Vo.Catelog3Vo> collect1 = categoryEntities1.stream().map(l3 -> {
                            Category2Vo.Catelog3Vo catelog3Vo = new Category2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        category2Vo.setCatalog3List(collect1);

                    }

                    return category2Vo;
                }).collect(Collectors.toList());
            }
            return collect;

        }));
        //设置过期时间，解决缓存雪崩
        redisTemplate.opsForValue().set("catalogJson", JSON.toJSONString(parent_cid), 1, TimeUnit.DAYS);

        return parent_cid;
    }

    /**
     * 本地锁，在分布式情况下，想要锁住所有，需要分布式锁
     * @return
     */
    private synchronized Map<String, List<Category2Vo>> getCatalogJsonFromDbWithLocalLock() {
        //加锁，为了控制缓存击穿，因此进来之后还要判断是否缓存中是否有
        return getDataFromDB();


    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList,Long parent_cid) {
//        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
        List<CategoryEntity> collect = selectList.stream().filter(item -> {
            return item.getParentCid() == parent_cid;
        }).collect(Collectors.toList());
        return collect;
    }


    private List<Long> findParentPath(Long catelogId, List<Long> paths){
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;
    }

    /**
     * 在categoryEntities中找出menu的子菜单
     * @param menu 需要返回谁的子菜单
     * @param categoryEntities 从哪里找出子菜单
     * @return 在categoryEntities中找出menu的子菜单
     */
    private List<CategoryEntity> getChildren(CategoryEntity menu, List<CategoryEntity> categoryEntities) {
        List<CategoryEntity> collect = categoryEntities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == menu.getCatId()
        ).map(categoryEntity -> {
            categoryEntity.setChildren(getChildren(categoryEntity, categoryEntities));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return collect;
    }


}